package com.lq.fastnews.model.api;


import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.lq.fastnews.utils.CacheUtil;

import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


@Module
public class ApiServiceModule {

    @Provides
    @Singleton
    ApiService provideApiService() {
        Retrofit retrofit = getRetrofit(ApiDefine.API_HOST);
        return retrofit.create(ApiService.class);
    }


    @NonNull
    private OkHttpClient getOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder. connectTimeout(CacheUtil.OUT_TIME, TimeUnit.SECONDS);
        builder. retryOnConnectionFailure(true);
        String saveDirPath = CacheUtil.getSaveDirPath();
        if(!TextUtils.isEmpty(saveDirPath))
        builder.cache(new Cache(new File(CacheUtil.getSaveDirPath()),CacheUtil.MAX_SIZE));
        builder.addInterceptor(new HttpCacheIntercepter());
        builder.addNetworkInterceptor(new TimeOutCacheIntercepter());
        return builder.build();
    }

    @NonNull
    private Retrofit getRetrofit(String host) {
        return new Retrofit.Builder().client(getOkHttpClient())
                .baseUrl(host)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }

}
